// 客户端入口，只在浏览器中运行
import { asyncDataFilter, createApp } from "./main";
import airbnb from "./db"; // 引入数据库和对象仓库

const { app, router, store } = createApp();

// 将客户端的app替换一下
if ((window as any).__INITIAL_STATE__) {
  store.replaceState((window as any).__INITIAL_STATE__);
}

// 将路由守卫移动到客户端中
router.beforeEach((to, from, next) => {
  airbnb.airbnbDB.openStore({
    ...airbnb.languageObjectStore,
    ...airbnb.userObjectStore
  }).then((res: any) => {
    console.log("初始化所有对象仓库", res);
    next();
  });
});

router.isReady().then(() => {
  // 页面不刷新也能执行数据预取
  router.beforeResolve((to, from, next) => {
    // 去的路由中所存在的组件
    let toComponents = router.resolve(to).matched.flatMap(record =>
      Object.values(record.components)
    );
    // 来的路由中所存在的组件
    let fromComponents = router.resolve(from).matched.flatMap(record =>
      Object.values(record.components)
    );
    // 需要防止二次预取 比较to、from他们之间的差异
    // 通过to和from比较出来的差异化数组
    let actived = toComponents.filter((c, i) => {
      return fromComponents[i] !== c;
    });
    if (!actived.length) {
      // 没有差异
      return next();
    }
    // console.log("开始loading");
    asyncDataFilter(actived, store, router.currentRoute).then(() => {
      // console.log("结束loading");
      next();
    });
  });
  // 先预取数据后 再在客户端以挂载页面的方式
  app.mount("#app");
});
